﻿using DBStructureGen.Common;
using DBStructureGen.DatabaseSchema;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DBStructureGen
{
    public partial class Connect : Form
    {
        private string _connString;

        Database _database = null;

        public Database Database
        {
            get { return _database; }
        }

        public Connect()
        {
            InitializeComponent();
        }

        private string GetConnectionString()
        {
            string conn = radiWinAuth.Checked ?
                string.Format("Data Source={0};Initial Catalog={1};Integrated Security=SSPI", textServer.Text, textDB.Text) :
                string.Format("Data Source={0};Initial Catalog={1};User Id={2};Paddword={3}", textServer.Text, textDB.Text, textLogin.Text, textPassword.Text);

            return conn;
        }

        private bool IsValidated()
        {
            errorProvider1.Clear();

            bool result = true;

            if ( string.IsNullOrWhiteSpace(textServer.Text) )
            {
                errorProvider1.SetError(textServer, "Enter SQL Server");
                result = false;
            }

            if ( string.IsNullOrWhiteSpace(textDB.Text) )
            {
                errorProvider1.SetError(textServer, "Select Database Name");
                result = false;
            }

            if ( string.IsNullOrWhiteSpace(textLogin.Text) && radioSQLServerAuth.Checked)
            {
                errorProvider1.SetError(textServer, "Enter Username");
                result = false;
            }

            if ( string.IsNullOrWhiteSpace(textPassword.Text) && radioSQLServerAuth.Checked )
            {
                errorProvider1.SetError(textServer, "Enter Password");
                result = false;
            }



            return result;
        }

        private void LoadSchema()
        {
            _connString = GetConnectionString();
            IDatabaseSchema dbSchema = new SqlDatabaseSchema();


            _database = dbSchema.GetDataBaseSchema(textServer.Text, textDB.Text, _connString);


            // Set in global Valiable
            DBStructureGenSettings.Instance.Database = _database;
            DBStructureGenSettings.Instance.ConnectionString = _connString;

            this.DialogResult = DialogResult.OK;
            this.Close();
           
        }

        private bool TestConnection()
        {
            string connectionString = GetConnectionString();
            try
            {
                return SqlDatabaseSchema.TestConnection(connectionString);
            }
            catch ( Exception ex )
            {
                MessageBox.Show("Unable to connect.\n" + ex.Message);
            }
            return false;

        }

        private void SaveSettings()
        {
            Properties.Settings.Default.Database = textDB.Text;
            Properties.Settings.Default.Password = textPassword.Text;
            Properties.Settings.Default.Server = textServer.Text;
            Properties.Settings.Default.SQLAuth = radioSQLServerAuth.Checked;
            Properties.Settings.Default.UserName = textLogin.Text;

            Properties.Settings.Default.Save();
        }

        private void LoadSettings()
        {
            textDB.Text = Properties.Settings.Default.Database;
            textServer.Text = Properties.Settings.Default.Server;
            radioSQLServerAuth.Checked = Properties.Settings.Default.SQLAuth;
            panel1.Enabled = radioSQLServerAuth.Checked;
            if ( radioSQLServerAuth.Checked )
            {
                textLogin.Text = Properties.Settings.Default.UserName;
                textPassword.Text = Properties.Settings.Default.Password;
            }
            else
            {
                radiWinAuth.Checked = true;
                textPassword.Text = "";
                textLogin.Text = "";
            }

        }

        private void LoginScreen_Load(object sender, EventArgs e)
        {
            LoadSettings();
        }

        private void rbtnSqlServerAuthentication_CheckedChanged(object sender, EventArgs e)
        {
            panel1.Enabled = radioSQLServerAuth.Checked;
        }

        private void btnConnection_Click(object sender, EventArgs e)
        {

            if ( !IsValidated() ) return;

            if ( TestConnection() )
            {
                try
                { // Load schema
                    LoadSchema();

                    // Save setting for future
                    SaveSettings();


                    // Close Form
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
                catch ( Exception ex )
                {
                    MessageBox.Show("Error to load schema.\n" + ex.Message, "Error to load schema", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }

        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }



    }
}
